<?php

namespace App\Console\Commands\OpenShop\Nsq;


use App\Enums\Check\CheckEnum;
use App\Enums\Common\NsqEnum;
use App\Models\OpenShop\InvestmentPromotion\OpenShopMainProcessModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSpaceDesignSoftOutfitMappingModel;
use App\Service\OpenShop\Feishu\ShopTagsService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Kuafu\Nsq\NsqSubscriber;
use NSQClient\Contract\Message;

class NsqSubMerchantOrderCloseCommand extends Command
{
    protected $signature = 'nsq:sub-merchant-order-close';

    protected $description = 'NSQ订阅商家订单关闭事件';

    public function handle()
    {
        (new NsqSubscriber(config('nsq.default.address')))
            ->sub(NsqEnum::TOPIC_KFOS_MERCHANT_ORDER_CLOSE, NsqEnum::CHANNEL_TIGER_SUB_MERCHANT_ORDER_CLOSE,
                function (Message $message) {

                    $this->doHandle($message->data());

                    $message->done();
                });
    }

    private function doHandle(array $data)
    {
        $sysType = $data['sys_type'] ?? 0;
        $shopId  = $data['shop_id'] ?? 0;

        if (!$sysType || !$shopId) {
            return;
        }

        $orderNo = (string)OpenShopMainProcessModel::query()->where('shopId', $shopId)->value('orderNo');

        // 设备关闭
        if ($sysType == CheckEnum::SYS_TYPE_OPEN_SHOP_EQUIPMENT) {
            Log::info("equipment closed:", $data);

            (new ShopTagsService($orderNo))->updateKfosTag();
            return;
        }

        // 软装关闭
        if ($sysType == CheckEnum::SYS_TYPE_OPEN_SHOP_DECORATE) {

            // 关闭soft
            $newOrderCode = $data['code'];
            $soft = OpenShopSpaceDesignSoftOutfitMappingModel::query()->where('newOrderCode', $newOrderCode)->first();
            if (!$soft) {
                return;
            }

            // 已关闭
            if ($soft->orderStatus == OpenShopSpaceDesignSoftOutfitMappingModel::ORDER_STATUS_3) {
                return;
            }
            $soft->orderStatus = OpenShopSpaceDesignSoftOutfitMappingModel::ORDER_STATUS_3;
            $soft->save();

            Log::info("soft closed: {$soft->id}", $data);

            // 更新软装支付标签
            (new ShopTagsService($orderNo))->updateSoftPayTag();
            return;
        }
    }
}
